package com.atguigu.srb.sms.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.atguigu.common.exception.Assert;
import com.atguigu.common.exception.BusinessException;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.srb.sms.service.SmsService;
import com.atguigu.srb.sms.util.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: Doream
 * @Date: 2022/2/3 13:55
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {
    @Override
    public void send(String mobile, String templateCode, Map<String, Object> param) {
        // 创建客户端连接阿里云
        DefaultProfile profile = DefaultProfile.getProfile(SmsProperties.REGION_ID, SmsProperties.KEY_ID, SmsProperties.KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);

        //固定参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");

        //相关参数
        request.putQueryParameter("PhoneNumbers",mobile); //手机号
        request.putQueryParameter("SignName",SmsProperties.SIGN_NAME); //申请阿里云 签名名称
        request.putQueryParameter("TemplateCode",SmsProperties.TEMPLATE_CODE); //申请阿里云 模板code
        request.putQueryParameter("TemplateParam", JSON.toJSONString(param)); //验证码数据，转换json数据传递


        //最终发送
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            HashMap<String,String> map = JSON.parseObject(data, HashMap.class);

            // 通信成功与否校验
            Assert.isTrue(response.getHttpResponse().isSuccess(),ResponseEnum.ALIYUN_SMS_RESPONSE_ERROR);

            // 返回结果校验
            String code = map.get("Code");
            String message = map.get("Message");
            // 业务失败的处理
            Assert.notEquals(code,"isv.BUSINESS_LIMIT_CONTROL",ResponseEnum.ALIYUN_SMS_LIMIT_CONTROL_ERROR);
            Assert.equals(code,"OK",ResponseEnum.ALIYUN_SMS_ERROR);

        } catch (ClientException e) {
            log.error("阿里云短信发送sdk调用失败:"+e.getErrCode()+","+e.getErrMsg());
            throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR,e);
        }
    }
}
